package org.yzbdl.lanius.orchestrate.serv.utils;

import org.yzbdl.lanius.orchestrate.common.exception.runtime.BusinessException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author zhuhongji@yzbdl.ac.cn
 * @date 2022-09-14 14:45
 */
public class ValidationUtils {

    private static final Validator VALIDATOR;

    static {
        VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验数据
     * @param object 校验对象
     * @param groups 校验的组
     * @throws IllegalArgumentException 异常抛出
     */
    public static void validateEntity(Object object, Class<?>... groups) throws IllegalArgumentException {
        Set<ConstraintViolation<Object>> constraintViolations = VALIDATOR.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            String msg = constraintViolations.stream().map(ConstraintViolation::getMessage)
                    .collect(Collectors.joining("||"));
            throw new BusinessException(msg);
        }
    }

}
